<?php
	
	class template {
	
		var $content;
		var $pathinfo;

		function template() {
			global $config, $smarty, $uri;

			$smarty->assign("config", $config);
			$smarty->assign("site_url", $config->site_url);
			$smarty->assign("site_index", $config->site_index);
			$smarty->assign("site_admin", $config->site_admin);
			$smarty->assign("site_upload", $config->dir_uploads);

			$this->run_template();
		}

		function run_template() {
			global $config, $smarty, $segment, $timestart, $uri;

			$para = $uri;
			
			
			


			// 找到要显示的模板路径
			while(!empty($uri)) {
				$uri = substr($uri, 0, strrpos($uri, '/'));
				$_path = MODULE_PATH."{$config->dir_template}/{$uri}";

				if(	file_exists($_path) && !is_dir($_path) ||
					file_exists("{$_path}/index.php") || 
					file_exists("{$_path}.php") ||
					file_exists("{$_path}/index.html") || 
					file_exists("{$_path}.html") ||
					file_exists("{$_path}/index.htm") || 
					file_exists("{$_path}.htm")
				) break;
			}

			
			$smarty->assign("segment", $_GET);
			$smarty->assign("uri", $uri);	// 存储在Smarty中,以备使用
			


			// 加载指定模块
			$this->pathinfo = $pathinfo = explode('/', $para);
			if (!empty($pathinfo[1])) $this->run_module($pathinfo[0], $pathinfo[1]);
			elseif (!empty($pathinfo[0])) $this->run_module($pathinfo[0]);

			// 加载指定页面
			$_path = MODULE_PATH."{$config->dir_template}/{$para}";	// 在 run_module 时可能对uri做过修改，再赋值	
			$smarty->assign("module_path", MODULE_PATH);	// 存储在Smarty中,以备使用
			
			
			
			if(file_exists("{$_path}.php")) { $this->content = $smarty->fetch("./{$para}.php"); }
			else if(file_exists("{$_path}/index.php")) { $this->content = $smarty->fetch("./{$para}/index.php"); }


		}

		function run_module($module="",$function="") {
			global $$module;
			if(!empty($module) && file_exists(MODULE_PATH."modules/mod.{$module}.php")) {
			    MODULE_PATH."modules/mod.{$module}.php";
				include_once(MODULE_PATH."modules/mod.{$module}.php");
				$obj = new $module();
				if(!empty($function) && method_exists($module, $function)) $obj->$function();
				else if (method_exists($module, "index")) $obj->index();
			}elseif(!empty($module) && file_exists(MODULE_PATH."modules/{$module}/index.php")) {
				include_once(MODULE_PATH."modules/{$module}/index.php");
				$$module = new $module();
			}
			
		}


	}

?>